package com.anxin.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.anxin.annotation.LoginRequire;
import com.anxin.annotation.RoleRequired;
import com.anxin.common.PageResult;
import com.anxin.common.Result;
import com.anxin.common.enums.RoleEnum;
import com.anxin.converter.PatientInfoConverter;
import com.anxin.entity.PatientInfo;
import com.anxin.entity.excel.PatientInfoExcel;
import com.anxin.security.util.SecurityUtils;
import com.anxin.service.ExcelService;
import com.anxin.service.FileService;
import com.anxin.service.PatientInfoService;
import com.anxin.system.dto.PatientInfoDTO;
import com.anxin.system.dto.UserInfoDTO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springdoc.core.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.Objects;

@Tag(name = "患者管理")
@RestController
@RequestMapping("/api/patient")
public class PatientInfoController extends BaseController {

    @Autowired
    private PatientInfoService patientInfoService;

    @Autowired
    private ExcelService excelService;

    @Autowired
    private FileService fileService;

    @Autowired
    private PatientInfoConverter patientInfoConverter;

    @Autowired
    private SecurityUtils securityUtils;

    @Operation(summary = "分页查询患者信息")
    @GetMapping("/page")
    @RoleRequired("ADMIN") // 限制只有 ADMIN 角色才能访问
    @LoginRequire
    public Result<PageResult<PatientInfo>> page(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "真实姓名") @RequestParam(required = false) String realName,
            @Parameter(description = "手机号") @RequestParam(required = false) String phone
    ){
        Page<PatientInfo> page = patientInfoService.page(pageNum, pageSize, realName, phone);
        return Result.page(page);
    }

    @Operation(summary = "查询患者信息")
    @GetMapping("/info")
    @LoginRequire
    public Result<PatientInfo> getInfo() {
        UserInfoDTO userInfoDTO = securityUtils.getCurrentUserInfo();
        PatientInfo patientInfo = patientInfoService.getByUserId(userInfoDTO.getUserId());
        return Result.success(patientInfo);
    }


    /**
     * 患者个人更新自己的信息
     */
    @Operation(summary = "更新患者信息")
    @PostMapping("/info")
    @LoginRequire
    public Result<String> updateInfo(@Valid @RequestBody PatientInfoDTO patientInfoDTO) {
        UserInfoDTO userInfoDTO = securityUtils.getCurrentUserInfo();
        // 只允许修改自己的信息
        if (!userInfoDTO.getUserId().equals(patientInfoDTO.getUserId())) {
            return Result.error("无权修改他人信息");
        }
        patientInfoService.updatePatientInfo(patientInfoDTO);
        return Result.success("更新成功");
    }


    @Operation(summary = "更新患者信息")
    @PostMapping("/update")
    @RoleRequired("ADMIN")
    @LoginRequire
    public Result<String> updatePatientInfo(@Valid @RequestBody PatientInfoDTO patientInfoDTO){
        UserInfoDTO userInfoDTO = securityUtils.getCurrentUserInfo();
        if (!Objects.equals(userInfoDTO.getRoleId(), RoleEnum.ADMIN.getCode())) {
            return Result.error("无权修改他人信息");
        }
        if (!(Objects.equals(RoleEnum.ADMIN.getCode(), userInfoDTO.getRoleId()))){
            throw new RuntimeException("权限不足");
        }
        patientInfoService.updatePatientInfo(patientInfoDTO);
        return Result.success("更新成功");
    }

    @Operation(summary = "删除患者信息")
    @DeleteMapping("/delete/{id}")
    @RoleRequired("ADMIN")
    @LoginRequire
    public Result<String> deletePatientInfo(@Parameter(description = "患者ID") @PathVariable String id) {
        UserInfoDTO userInfoDTO = securityUtils.getCurrentUserInfo();
        if (!Objects.equals(userInfoDTO.getRoleId(), RoleEnum.ADMIN.getCode())) {
            return Result.error("无权删除他人信息");
        }
        patientInfoService.deletePatientInfo(id);
        return Result.success("删除成功");
    }


    @Operation(summary = "导入患者Excel数据")
    @PostMapping("/import")
    public Result<String> importExcel(@Parameter(description = "Excel文件") @RequestParam("file") MultipartFile file) {
        try {
            // 导入Excel数据
            List<PatientInfoExcel> excelList = excelService.importExcel(file, PatientInfoExcel.class);
            // 转换为实体类
            List<PatientInfo> patientInfoList = patientInfoConverter.toEntityList(excelList);
            // 保存数据
            patientInfoService.saveBatch(patientInfoList);
            return Result.success("导入成功");
        } catch (Exception e) {
            return Result.error("导入失败：" + e.getMessage());
        }
    }

    @GetMapping("/export")
    @RoleRequired("ADMIN")
    @LoginRequire
    public void exportExcel(HttpServletResponse response) {
        UserInfoDTO userInfoDTO = securityUtils.getCurrentUserInfo();
        if (!Objects.equals(userInfoDTO.getRoleId(), RoleEnum.ADMIN.getCode())) {
            Result.error("无权删除他人信息");
            return;
        }
        try {
            // 查询所有数据
            List<PatientInfo> patientInfoList = patientInfoService.list();
            List<PatientInfoExcel> excelList = patientInfoConverter.toExcelList(patientInfoList);

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("患者信息"+ IdUtil.getSnowflakeNextIdStr(), StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 写出到响应流
            EasyExcel.write(response.getOutputStream(), PatientInfoExcel.class)
                    .sheet("患者信息")
                    .doWrite(excelList);
        } catch (Exception e) {
            try {
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @GetMapping("/download/{fileName}")
    public byte[] downloadFile(@PathVariable String fileName) {
        try {
            return fileService.downloadFile(fileName);
        } catch (Exception e) {
            throw new RuntimeException("下载文件失败", e);
        }
    }
}
